<?php


namespace dsp\iterator;


class AlphabeticalOrderIterator implements \Iterator
{

    private $collection;

    private $position = 0;

    private $reverse = false;

    public function __construct($collection, $reverse = false)
    {
        echo '=========== 创建迭代器' . PHP_EOL;
        $this->collection = $collection;
        $this->reverse = $reverse;
    }


    /**
     * @inheritDoc
     */
    public function current()
    {
        echo '=========== 获取当前元素' . PHP_EOL;
        return $this->collection->getItems()[$this->position];
    }

    /**
     * @inheritDoc
     */
    public function next()
    {
        echo '=========== 获取下一个元素' . PHP_EOL;
        $this->position = $this->position + ($this->reverse ? -1 : 1);
    }

    /**
     * @inheritDoc
     */
    public function key()
    {
        echo '=========== 获取当前元素的键值' . PHP_EOL;
        return $this->position;
    }

    /**
     * @inheritDoc
     */
    public function valid()
    {
        echo '=========== 判断当前元素是否有效' . PHP_EOL;
        return isset($this->collection->getItems()[$this->position]);
    }

    /**
     * @inheritDoc
     */
    public function rewind()
    {
        echo '=========== 重置当前元素' . PHP_EOL;
        $this->position = $this->reverse ? count($this->collection->getItems()) - 1 : 0;
    }
}